class Solution
{
public:
    vector<int> advantageCount(vector<int> &nums1, vector<int> &nums2)
    {
        int n = nums1.size();
        vector<int> result(n);
        vector<int> nums2Id(n);
        iota(nums2Id.begin(), nums2Id.end(), 0);
        sort(nums1.begin(), nums1.end());
        sort(nums2Id.begin(), nums2Id.end(), [&](int i1, int i2)
             { return nums2[i1] < nums2[i2]; });
        int toCover = 0;
        int toDiscard = n - 1;
        for (int i = 0; i < n; ++i)
        {
            if (nums1[i] > nums2[nums2Id[toCover]])
            {
                result[nums2Id[toCover]] = nums1[i];
                ++toCover;
            }
            else
            {
                result[nums2Id[toDiscard]] = nums1[i];
                --toDiscard;
            }
        }
        return result;
    }
};